﻿/// *******************************
/// 作者：reazhuang 庄星睿
/// 联系方式：reazhuang@outlook.com
/// 文件说明
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace Security
{
	public class HmacSHA256Sample
	{
		/// <summary>
		/// 返回经Base64加密的文本
		/// </summary>
		/// <param name="text"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public string EncryToBase64(string text, string key)
		{
			var rs = EncryToByteArray(text, key);
			return Convert.ToBase64String(rs);
		}

		/// <summary>
		/// 返回字节数组
		/// </summary>
		/// <param name="text"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public byte[] EncryToByteArray(string text, string key)
		{
			HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
			return hmac.ComputeHash(Encoding.UTF8.GetBytes(text));
		}

		/// <summary>
		/// 返回文本
		/// </summary>
		/// <param name="text"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public string EncryToNormal(string text, string key)
		{
			var rs = EncryToByteArray(text, key);
			return Convert.ToString(rs);
		}
	}
}
